package com.selfdriving;

import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalBitmap;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.selfdriving.activity.BaseActivity;
import com.selfdriving.bean.Preference;
import com.selfdriving.dialog.FlippingLoadingDialog;
import com.selfdriving.utils.LogUtil;
import com.selfdriving.utils.NetworkCheck;

public abstract class BaseFragmentActivity extends FragmentActivity
{
	protected FlippingLoadingDialog mLoadingDialog;
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	protected DisplayImageOptions options;
	/**
	 * 屏幕的宽度、高度、密度
	 */
	protected int mScreenWidth;
	protected int mScreenHeight;
	protected float mDensity;
	public static String LOGTAG = BaseActivity.class.getSimpleName();
	protected NetworkCheck networkCheck;
	public static SharedPreferences mShared;

	public SharedPreferences sharedPrefs;

	public static SharedPreferences.Editor mEditor;

	protected LinearLayout.LayoutParams layoutParams;

	protected BaseApplication mApplication;

	protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();

	public BaseFragmentActivity()
	{
		super();
		LOGTAG = this.getClass().getSimpleName();
	}

	protected Handler mHanler;

	private ProgressDialog mProgressDialog;

	private final ArrayList<LifeCycleListener> mListeners = new ArrayList<LifeCycleListener>();

	protected FinalBitmap fb;

	public static interface LifeCycleListener
	{
		public void onActivityCreated(BaseActivity activity);

		public void onActivityDestroyed(BaseActivity activity);

		public void onActivityPaused(BaseActivity activity);

		public void onActivityResumed(BaseActivity activity);

		public void onActivityStarted(BaseActivity activity);

		public void onActivityStopped(BaseActivity activity);
	}

	public static class LifeCycleAdapter implements LifeCycleListener
	{
		public void onActivityCreated(BaseActivity activity)
		{
		}

		public void onActivityDestroyed(BaseActivity activity)
		{
		}

		public void onActivityPaused(BaseActivity activity)
		{
		}

		public void onActivityResumed(BaseActivity activity)
		{
		}

		public void onActivityStarted(BaseActivity activity)
		{
		}

		public void onActivityStopped(BaseActivity activity)
		{
		}
	}

	public void addLifeCycleListener(LifeCycleListener listener)
	{
		if (mListeners.contains(listener))
			return;
		mListeners.add(listener);
	}

	public void removeLifeCycleListener(LifeCycleListener listener)
	{
		mListeners.remove(listener);
	}

	public void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask)
	{
		mAsyncTasks.add(asyncTask.execute());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		networkCheck = new NetworkCheck(this);
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		mScreenWidth = metric.widthPixels;
		mScreenHeight = metric.heightPixels;
		mDensity = metric.density;
		mHanler = new Handler();
		mShared = this.getSharedPreferences(Preference.PREFERENCES_NAME, 0);
		mEditor = mShared.edit();
		mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
		mApplication = (BaseApplication) getApplication();
		options = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.showImageOnLoading(R.drawable.default_loading)
				.showImageForEmptyUri(R.drawable.default_loading)
				.showImageOnFail(R.drawable.default_loading)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		fb = FinalBitmap.create(getApplicationContext());
	}

	/** 初始化视图 **/
	protected abstract void initViews();

	/** 初始化事件 **/
	protected abstract void initEvents();

	public static boolean putString(final String entry, String value,
			boolean commit)
	{
		if (mEditor == null)
		{
			return false;
		}
		mEditor.putString(entry, value);
		if (commit)
		{
			return mEditor.commit();
		}
		return true;
	}

	public static boolean putInt(final String entry, int value, boolean commit)
	{
		if (mEditor == null)
		{
			return false;
		}
		mEditor.putInt(entry, value);
		if (commit)
		{
			return mEditor.commit();
		}
		return true;
	}

	public static boolean putBoolean(final String entry, boolean value,
			boolean commit)
	{
		if (mEditor == null)
		{
			return false;
		}
		mEditor.putBoolean(entry, value);
		if (commit)
		{
			return mEditor.commit();
		}
		return true;
	}

	public boolean getBoolean(final String entry, boolean defaultValue)
	{
		if (mEditor == null)
		{
			return defaultValue;
		}
		try
		{
			return mShared.getBoolean(entry, defaultValue);
		} catch (Exception e)
		{
			e.printStackTrace();
			return defaultValue;
		}
	}

	public static String getString(final String entry, String defaultValue)
	{
		if (mEditor == null)
		{
			return defaultValue;
		}
		try
		{
			return mShared.getString(entry, defaultValue);
		} catch (Exception e)
		{
			e.printStackTrace();
			return defaultValue;
		}
	}

	public int getInt(final String entry, int defaultValue)
	{
		if (mEditor == null)
		{
			return defaultValue;
		}
		try
		{
			return mShared.getInt(entry, defaultValue);
		} catch (Exception e)
		{
			e.printStackTrace();
			return defaultValue;
		}
	}

	@Override
	protected void onDestroy()
	{
		LogUtil.d("[BaseActivity onDestroy] : " + LOGTAG);
		super.onDestroy();
		cancelInProgressOnUiThread();
	}

	@Override
	protected void onStart()
	{
		LogUtil.d("[BaseActivity onStart] : " + LOGTAG);
		super.onStart();
	}

	@Override
	protected void onPause()
	{
		LogUtil.d("[BaseActivity onPause] : " + LOGTAG);
		super.onPause();
	}

	@Override
	protected void onResume()
	{
		LogUtil.d("[BaseActivity onResume] : " + LOGTAG);
		super.onResume();
	}

	@Override
	protected void onStop()
	{
		super.onStop();
		LogUtil.d("[BaseActivity onStop] : " + LOGTAG);
	}

	private Toast toast;

	/**
	 * 显示toast 短时
	 * 
	 * @param message
	 */
	public void showToast(String message)
	{
		if (toast == null)
		{
			toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		} else
		{
			if (toast.getView() != null
					&& toast.getView().getWindowToken() != null)
			{
				toast.cancel();
			}
			toast.setText(message);
			toast.setDuration(Toast.LENGTH_SHORT);
		}
		toast.show();
	}

	/** 含有标题、内容、两个按钮的对话框 **/
	protected AlertDialog showAlertDialog(String title, String message,
			String positiveText,
			DialogInterface.OnClickListener onPositiveClickListener,
			String negativeText,
			DialogInterface.OnClickListener onNegativeClickListener)
	{
		AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle(title)
				.setMessage(message)
				.setPositiveButton(positiveText, onPositiveClickListener)
				.setNegativeButton(negativeText, onNegativeClickListener)
				.show();
		return alertDialog;
	}

	/**
	 * 封装 handler消息
	 */
	public void getHanderMessage(Handler handler, int what, String details)
	{
		handler.sendMessage(Message.obtain(handler, what, details));
	}

	public SharedPreferences getSharedPreferences()
	{
		return sharedPrefs;
	}

	/**
	 * 线程取消进度条
	 */
	public void cancelInProgressOnUiThread()
	{
		mHanler.post(new Runnable()
		{
			@Override
			public void run()
			{
				cancelInProgress();
			}
		});
	}

	/**
	 * 取消进度条
	 */
	public void cancelInProgress()
	{
		synchronized (this)
		{
			if (mProgressDialog != null)
			{
				mProgressDialog.cancel();
				mProgressDialog = null;
			}
		}
	}

	public boolean isLogin()
	{
		if (mApplication.user != null)
		{
			return true;
		} else
		{
			return false;
		}
	}

	/** 短暂显示Toast提示(来自String) **/
	protected void showShortToast(String text)
	{
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}

	/** 通过Class跳转界面 **/
	protected void startActivity(Class<?> cls)
	{
		startActivity(cls, null);
	}

	/** 含有Bundle通过Class跳转界面 **/
	protected void startActivity(Class<?> cls, Bundle bundle)
	{
		Intent intent = new Intent();
		intent.setClass(this, cls);
		if (bundle != null)
		{
			intent.putExtra("bundle", bundle);
		}
		startActivity(intent);
	}

	protected void dismissLoadingDialog()
	{
		if (mLoadingDialog.isShowing())
		{
			mLoadingDialog.dismiss();
		}
	}

	protected void showLoadingDialog(String text)
	{
		if (text != null)
		{
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}
}
